package com.swm.julie.rest.crud.twitt.delete;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class DeleteTwitt {

	String indexDir;
	
	public DeleteTwitt()
	{
		
	}
	
	/**
	 * Delete the twitts having the id from the index directory.
	 * It doesn't need to the same directory with the search index directory.
	 * Return completeness of the process.
	 * If there is not twitt with the id, it means that non-existence of the twitt then return true.
	 * @param twittId indexed id of the twitt 
	 * @return success - true, failure - false
	 * @throws IOException 
	 */
	public boolean delete(String twittId) throws IOException
	{
		if(indexDir == null || indexDir.length() == 0)
		{
			return false;
		}
		
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexReader reader = IndexReader.open(dir, false);
		
		int deleted = reader.deleteDocuments(new Term("id", twittId));
		
		reader.close();
		dir.close();
		
		System.out.println("DeleteTwitt.delete() : delete '"+ deleted + "' twitts with the id, " + twittId); 
		
		return true;
	}

	/**
	 * Set a index directory for delete.
	 * It must be calle before delete for set the directory.
	 * @param indexDir - index directory for delete indexed of the twitt 
	 */
	public void setIndexDir(String indexDir) {
		this.indexDir = indexDir;
	}
}
